<script setup lang="ts">
import { libraryaOptions, exportUser, tenOptions } from "@/api/wrong/BookLose";
import type { RequestParams, LibraryPageVo } from "@/api/wrong/type";
import { ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
const hasRole = (role: any) => {
  return useStore.user.roles.includes(role);
};
const libraryList = ref([] as LibraryPageVo[]); //列表数据
const queryFormRef = ref(); //refForm
const tenn = ref([] as any);
const total = ref();
const loading = ref(false);
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  taskNo: "",
  bookIndex: "",
} as RequestParams);
const resetQuery = () => {
  // 1. 清空查询条件
  queryParams.value = { pageNum: 1, pageSize: 10, taskNo: "" } as RequestParams; // 所有字段清空

  // 2. 重新拉一次下拉框（可选，防止新增任务后列表未更新）
  Options();

  // 3. 不自动搜索，保持列表为空（符合“重置即清空”习惯）
  libraryList.value = [];
};
/**
 * 列表数据
 */
const getList = async () => {
  const { taskNo, bookIndex } = queryParams.value;

  // 判断是否有任一条件非空（“或”关系）
  if (!taskNo && !bookIndex) {
    ElMessage.warning("搜素不能为空");
    return;
  }

  queryParams.value.taskNo = queryParams.value.taskNo;
  const res = await libraryaOptions(queryParams.value);
  libraryList.value = res.data.records!;
  total.value = res.data.total;
  //console.log(res.data.records, "分页列表");
  //console.log(queryParams.value, "列表");
};
/**
 * 列表数据
 */
const Options = async () => {
  const res = await tenOptions(useStore.encryptedData);
  tenn.value = res.data;
  //console.log(res, "10分页列表");

  // console.log(res.data.list, "分页列表");
  // console.log(queryParams.value);
};
/**
 * 导出用户
 */
function handleUserExport() {
  exportUser(queryParams.value.taskNo).then((response: any) => {
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    });
    const a = document.createElement("a");
    const href = window.URL.createObjectURL(blob); // 下载的链接
    a.href = href;
    a.download = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    ); // 获取后台设置的文件名称
    document.body.appendChild(a);
    a.click(); // 点击导出
    document.body.removeChild(a); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  });
}
const isSearchDisabled = computed(() => {
  const { taskNo, bookIndex } = queryParams.value;
  return !taskNo && !bookIndex;
});
// 控制序号
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
onMounted(() => {
  //  getList();
  Options();
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
</script>

<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="盘点编号">
          <el-select
            style="width: 200px"
            clearable
            v-model="queryParams.taskNo"
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入查询报表"
          >
            <el-option
              v-for="item in tenn"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="索书号">
          <el-input
            :disabled="!queryParams.taskNo"
            v-model="queryParams.bookIndex"
            placeholder="请输入索书号"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header>
        <el-button
          :disabled="isSearchDisabled"
          type="success"
          @click="handleUserExport"
          v-if="hasRole('ADMIN')"
          >导出</el-button
        >
      </template>
      <el-table v-loading="loading" :data="libraryList" :border="true">
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />

        <el-table-column label="索书号" prop="bookIndex" :align="'center'" />
        <el-table-column label="图书编号" prop="bookCode" :align="'center'" />
        <el-table-column label="图书名称" prop="bookName" :align="'center'" />
        <el-table-column
          label="在架位置"
          prop="shouldShelf"
          :align="'center'"
        />
        <!-- <el-table-column label="库存数量" prop="bookCount" :align="'center'" /> -->

        <!-- <el-table-column label="盘点编号" prop="taskNo" :align="'center'" /> -->
      </el-table>
      <el-pagination
        v-if="total > 0"
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}
</style>
